package com.example.tcpLearn.tcp4;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 多客户端与服务端通信：服务端
 */
public class Server {
    public static void main(String[] args) throws IOException {

        System.out.println("服务端启动...");

        ServerSocket serverSocket = new ServerSocket(8888);

        while (true) {
            /**
             * 接受客户端的socket
             */
            Socket socket = serverSocket.accept();
            if (socket == null) {
                serverSocket.close();
                break;
            }
            System.out.println("客户端" + socket.getRemoteSocketAddress() + "上线了");
            /**
             * 创建一个线程，处理客户端的socket
             */
            new Thread(() -> {
                try {
                    InputStream inputStream = socket.getInputStream();
                    DataInputStream dataInputStream = new DataInputStream(inputStream);

                    OutputStream outputStream = socket.getOutputStream();
                    DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
                    while (true) {
                        try {
                            String string = dataInputStream.readUTF();
                            System.out.println("服务端已收到数据：" + string);
                            System.out.println("=============================");
                        } catch (Exception e) {
                            System.out.println(socket.getRemoteSocketAddress() + "离线了");
                            dataOutputStream.close();
                            dataInputStream.close();
                            socket.close();
                            break;
                        }
                        dataOutputStream.writeUTF("服务端已收到数据");
                        dataOutputStream.flush();
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }

    }
}
